package monte.cs;

import monte.Battle;
import monte.Team;
import monte.exception.NoResultsException;

import java.util.ArrayList;
import java.util.LinkedList;

public class SingleFailureCS implements CompetitionSystem {

    private LinkedList<Battle> battles;
    private ArrayList<Integer> topTeams;

    @Override
    public void simulate(ArrayList<Team> teams) throws NoResultsException {
        if (teams.size() != 10) {
            throw new NoResultsException("该赛制，需要参数队伍为10支");
        }
        battles = new LinkedList<>();
        topTeams = new ArrayList<>(4);
        Battle battle_79 = new Battle(7, 9);
        Battle battle_68 = new Battle(6, 8);
        int winner_79 = getSimulate(teams, battles, battle_79);
        int winner_68 = getSimulate(teams, battles, battle_68);

        Battle battle_579 = new Battle(winner_79, 5);
        Battle battle_468 = new Battle(winner_68, 4);
        int winner_468 = getSimulate(teams, battles, battle_468);
        int winner_579 = getSimulate(teams, battles, battle_579);

        Battle battle_2468 = new Battle(winner_468, 2);
        Battle battle_3579 = new Battle(winner_579, 3);
        int winner_2468 = getSimulate(teams, battles, battle_2468);
        int winner_3579 = getSimulate(teams, battles, battle_3579);

        Battle battle_02468 = new Battle(winner_2468, 0);
        Battle battle_13579 = new Battle(winner_3579, 1);
        int winner_02468 = getSimulate(teams, battles, battle_02468);
        int winner_13579 = getSimulate(teams, battles, battle_13579);
        int loser_02468 = winner_02468 != winner_2468 ? winner_2468 : 0;
        int loser_13579 = winner_13579 != winner_3579 ? winner_3579 : 1;

        //季军赛
        Battle playoffBattle = new Battle(loser_02468, loser_13579);
        int winner_playoff = getSimulate(teams, battles, playoffBattle);
        int loser_playoff = winner_playoff == loser_02468 ? loser_13579 : loser_02468;

        //冠军赛
        Battle championBattle = new Battle(winner_02468, winner_13579);
        int winner_champion = getSimulate(teams, battles, championBattle);
        int loser_champion = winner_champion == winner_02468 ? winner_13579 : winner_02468;

        //设置前四名队伍
        topTeams.add(winner_champion);
        topTeams.add(loser_champion);
        topTeams.add(winner_playoff);
        topTeams.add(loser_playoff);
    }

    @Override
    public LinkedList<Battle> getResults() throws NoResultsException {
        if (battles == null)
            throw new NoResultsException("还没有开始模拟");
        return battles;
    }

    @Override
    public ArrayList<Integer> getTopTeams() throws NoResultsException {
        return topTeams;
    }

    @Override
    public CompetitionSystem emptyObject() {
        return new SingleFailureCS();
    }

    private int getSimulate(ArrayList<Team> teams, LinkedList<Battle> battles, Battle battle) {
        battles.add(battle);
        return battle.simulate(teams);
    }
}
